package main


func snakesAndLadders(board [][]int) int {
	n := len(board)
	var dfs func(i int, cnt int) 
	ans := n * n
	dfs = func(i int, cnt int) {
		if i == n * n {
			ans = min(ans, cnt)
			return
		}
		r, c := 0, 0
		for j := i + 1; j <= min(i + 6, n * n); j++ {
			r = (n - 1) - (j - 1) / n
			if (j - 1) / n % 2 == 0 {
				c = (j - 1) % n
			} else {
				c = n - 1 - (j - 1) % n
			}
			if board[r][c] != -1 {
				dfs(board[r][c], cnt + 1)
			} else {
				dfs(j, cnt + 1)
			}
		}
	}
	dfs(1, 0)
	return ans
}